import dayjs from 'dayjs'
import { getToken } from '@/utils/auth'
export const getTaskGroup = (task) => {
	const { createID, assignId, fromId } = task
	if (fromId) {
		return 'tome'
	} else if (assignId) {
		return 'assign'
	} else {
		return 'myday'
	}

}
const setAlarms = (alarmList) => {
	plus.push.clear()
	alarmList.forEach(item => {
		const { noticeDateTime, taskContent } = item
		const delaySeconds = dayjs(noticeDateTime).diff(dayjs(), 'seconds')
		let options = {
			"cover": true,
			"delay": delaySeconds,
			'title': '任务提醒',
			'sound': 'system'
		};
		let payload = JSON.stringify(item);
		plus.push.createMessage(taskContent, payload, options);
	})
	// plus.push.addEventListener("click", (msg) => {
	// 	uni.navigateTo({ // 登陆成功后，点击消息跳转到消息列表页
	// 		url: "/pages/index/index",
	// 		success: function(res) {
	// 			console.log('跳转成功', res);
	// 		},
	// 		fail: function(err) {
	// 			console.log('跳转失败', err);
	// 		},
	// 	});
	// }, false);
}

const getAlramList = (taskList) => {

	const alarmList = []
	const usefullTask = taskList.filter(item => {
		const { deleted, noticeDateTime } = item
		const noDelete = !deleted // 未脱机删除的
		const noOverTime = noticeDateTime && (dayjs(noticeDateTime) > dayjs()) // 晚于当前时间的
		return noDelete && noOverTime
	})
	usefullTask.forEach(item => {

		alarmList.push(item)
	})

	return alarmList
}

export const alarmHandler = (newList) => {
	if (!getToken()) return
	const alarmList = getAlramList(newList)
	setAlarms(alarmList)
}

export const getNowTime = () => {
	return dayjs().format('YYYY-MM-DD HH:mm:ss')
}


export const getTempId = () => {
	return Date.now() + Math.floor(Math.random() * 100000)
}

export const createNewTask = (props, revert = false) => {
	const task = {
		taskId: getTempId(),
		"taskContent": null,
		"flag": 0,
		"noticeDateTime": null,
		"endDateTime": null,
		"fileData": null,
		"note": null,
		"finishStatus": 0,
		"confirmUserId": null,
		"confirmDateTime": null,
		"createDateTime": dayjs().format('YYYY-MM-DD HH:mm:ss'),
		"assignId": null,
		"shareDateTime": null,
		"fromId": null,
		"noteUpdateTime": null,
		"repeatCircle": null,
		"repeatUnit": null,
		"repeatExtFields": null,
		"nextRepeatTime": null,
		"deadTime": null,
		"repeatFlag": null,
		"fileList":[],
		steps: []
	}
	return Object.assign(task, props)
}



export const timeSimpleTxt = (hours) => {
	if (hours < 7) {
		return '凌晨'
	} else if (hours < 12) {
		return '上午'

	} else if (hours < 13) {
		return '中午'

	} else if (hours < 18) {
		return '下午'
	} else if (hours < 24) {
		return '晚上'
	}
}
export const calcToday = () => {
	const hours = dayjs().hour()
	if ((24 - hours) < 3 || hours < 6) {
		return ''
	} else {
		const txt = timeSimpleTxt(hours)
		return `(${txt}${hours<6?6:hours+3}点)`
	}
}

export const dateSimpleTxt = (date) => {
	const currentDate = dayjs().startOf('day');
	const target = dayjs(date).startOf('day');

	if (target.isSame(currentDate, 'day')) {
		return '今天';
	} else if (target.isSame(currentDate.add(1, 'day'), 'day')) {
		return '明天';
	} else if (target.isSame(currentDate.add(-1, 'day'), 'day')) {
		return '昨天'
	} else {
		return dayjs(date).format('M月D日 dddd')
	}
}

export const updateTimeFormat = (date) => {
	const current = dayjs()
	const target = dayjs(date)
	const diffMinite = current.diff(target, 'minutes')

	if (diffMinite < 1) {
		return '更新于刚刚'
	} else if (diffMinite < 60) {
		return `更新于${diffMinite}分钟前`
	} else {
		const diffHours = current.diff(target, 'hours')
		if (diffHours < 24) {
			return `更新于${diffHours}小时前`
		} else {

			return `更新于${dayjs(date).format('M月D日 dddd')}`
		}

	}

}




export const getNextWorkingDay = (start = dayjs()) => {
	// 获取当前日期
	const currentDate = dayjs(start);
	// 获取当前日期是一周中的第几天
	const dayOfWeek = currentDate.day();

	let nextWorkingDay;

	// 根据当前是周几来计算下一个工作日
	switch (dayOfWeek) {


		// 周五，下一个工作日是下周一，加 3 天
		case 5:
			nextWorkingDay = currentDate.add(3, 'day');
			break;
			// 周六，下一个工作日是周一，加 2 天
		case 6:
			nextWorkingDay = currentDate.add(2, 'day');
			break;
		default:
			nextWorkingDay = currentDate.add(1, 'day');
			break;
	}

	return nextWorkingDay.format("YYYY-MM-DD HH:mm:ss");
}



export const nextCustomWeekDay = (start, daystr, circle = 1) => {
	const customWeeks = daystr.split(";") //[0,2,6]
	const currentDate = dayjs(start);
	// 获取当前日期是一周中的第几天
	const dayOfWeek = currentDate.day();
	const nextDay = customWeeks.find(item => item > dayOfWeek) || customWeeks[0]


	// 计算到下一个星期 n 的天数差
	let daysToAdd;
	if (nextDay > dayOfWeek) {
		daysToAdd = nextDay - dayOfWeek;
	} else {
		daysToAdd = 7 - (dayOfWeek - nextDay);
	}

	// 如果天数差为 0，说明当前就是目标星期，需要再加 7 天到下一周
	if (daysToAdd === 0) {
		daysToAdd = 7;
	}
	console.log(nextDayOfWeek, 'nextDayOfWeek')
	// 计算下一个星期 n 的日期
	const nextDayOfWeek = currentDate.add(daysToAdd, 'day').add(circle - 1, 'week').startOf('day').format("YYYY-MM-DD HH:mm:ss");
	return nextDayOfWeek;


}

export const nextCircleDate = (start, cirlceUnit, circle = 1) => {
	const startDay = dayjs(start || dayjs())
	return startDay.add(circle, cirlceUnit).startOf('day').format("YYYY-MM-DD HH:mm:ss")
}

export const nextRepeatDay = (repeatInfo, start) => {
	const startTime = start || dayjs()
	const { repeatCircle, repeatUnit, repeatExtFields } = repeatInfo
	if (['day', 'month', 'year'].includes(repeatUnit)) {
		return nextCircleDate(startTime, repeatUnit, repeatCircle)
	} else if (repeatUnit === 'workday') {
		return getNextWorkingDay(startTime)
	} else if (repeatUnit === 'week') {
		return nextCustomWeekDay(startTime, repeatExtFields, repeatCircle)
	}

}

export const weekMap = {
	"0": "星期日",
	"1": "星期一",
	"2": "星期二",
	"3": "星期三",
	"4": "星期四",
	"5": "星期五",
	"6": "星期六",
}

export const formatFileSize = (fileSize) => {
	if (fileSize < 1024) {
		return fileSize + 'B';
	}
	const units = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
	let exp = Math.floor(Math.log(fileSize) / Math.log(1024));
	let formattedSize = (fileSize / Math.pow(1024, exp)).toFixed(1);
	return formattedSize + ' ' + units[exp - 1];
}

// 定义文件扩展名到通俗名的映射对象
const fileTypeMap = {
	// 图片类型
	jpg: '图片',
	jpeg: '图片',
	png: '图片',
	gif: '图片',
	bmp: '图片',
	svg: '图片',
	// 文档类型
	doc: 'Word 文档',
	docx: 'Word 文档',
	xls: 'Excel 表格',
	xlsx: 'Excel 表格',
	ppt: 'PowerPoint 演示文稿',
	pptx: 'PowerPoint 演示文稿',
	pdf: 'PDF 文档',
	txt: '文本文件',
	zip: '压缩文件',
	rar: '压缩文件',
	"7z": '压缩文件',
	// 视频类型
	mp4: '视频',
	avi: '视频',
	mov: '视频',
	mkv: '视频',
	flv: '视频',
	// 音频类型
	mp3: '音频',
	wav: '音频',
	ogg: '音频',
	wma: '音频'
};

export const getFileTxtType = (ext) => {
	const extName = ext ? ext.replace('.', '') : ''
	return fileTypeMap[extName.toLowerCase()] || '其它'
}

export const getFileType = (ext) => {
	if (ext) {
		return ext.replace('.', '').toUpperCase()
	} else {
		return ''
	}
}